import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { resetRouter } from './router'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login']

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      // 检查是否已获取用户角色
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          // 获取用户信息
          const { roles } = await store.dispatch('user/getInfo')
          
          // 生成动态路由（确保返回标准化小写路径）
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
          
          // 清空旧路由（防止重复添加）
          resetRouter()
          
          // 添加新路由
          accessRoutes.forEach(route => {
            router.addRoute(route)
          })
          
          // 关键修复：强制重定向到原始目标路径
          // Use router.replace to ensure navigation is re-triggered with new routes
          router.replace(to.fullPath) // Use router.replace for explicit navigation
          
        } catch (error) {
          await store.dispatch('user/resetToken')
          Message.error('登录状态已失效，请重新登录')
          // 标准化重定向路径为小写
          const redirectPath = to.path.toLowerCase()
          next(`/login?redirect=${encodeURIComponent(redirectPath)}`)
          NProgress.done()
        }
      }
    }
  } else {
    // 白名单处理
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // 标准化重定向路径
      const redirectPath = to.path.toLowerCase()
      next(`/login?redirect=${encodeURIComponent(redirectPath)}`)
      NProgress.done()
    }
  }
})